package yns.springboot.guide.demo.controller.data.mongodb;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import tools.jackson.databind.ObjectMapper;



@RestController
@RequestMapping("/mongodb/template")
public class TestMongoDBTemplateController {
	
	// http://localhost:8080/mongodb/template
	// http://localhost:8080/mongodb/template/add
	// http://localhost:8080/mongodb/template/search
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static final String MONGODB_COLLECTION = "test";

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@GetMapping()
	public String testMongodb() {
		
		String str = mongoTemplate.getCollection(MONGODB_COLLECTION).find().first().toJson();
		logger.info(str);
				
		return "test.mongodb.template--testMongodb";
	}
	
	@GetMapping("/add")
	public String testMongodbAdd() {
		
		Map<String, String> map = new HashMap<>();
		
		map.put("info", "test");
		map.put("time", LocalDateTime.now().toString());
		
		String json = objectMapper.writeValueAsString(map);
		logger.info(json);
		
		mongoTemplate.insert(json,MONGODB_COLLECTION);

		return "test.mongodb.template--testMongodbAdd";
	}
	
	@GetMapping("/search")
	public String testMongodbSearch(@RequestParam(value = "search") String search) {
				
		Criteria criteria = Criteria.where("info").is("test");
		
		Query query = new Query();
		query.addCriteria(criteria).with(Sort.by("time").descending());

		Object object = mongoTemplate.findOne(query, String.class,MONGODB_COLLECTION);

		logger.info(object.toString());
		
		
		return "test.mongodb.template--testMongodbSearch";
	}
	

}
